import {message} from '@common/assets/js/resetMessage';
import request from './request.js';
import constants from '@common/api/constants';
import utils from "./utils.js";
import {download} from "./download.js";

const procArraybuffer = arraybuffer => {
    return new Promise(resolve => {
        let blob = new Blob([arraybuffer], {
            type: 'application/json',
        });
        const reader = new FileReader();
        reader.onload = e => {
            try {
                const json = JSON.parse(e.target.result);
                if (json.code === 1000) {
                    location.hash = '/login';
                } else {
                    if (utils.isNotEmpty(json.message) && json.message.startsWith('{') && json.message.endsWith('}')) {
                        let msgJson = JSON.parse(json.message);
                        resolve({
                            json: true,
                            data: msgJson,
                        });
                    } else {
                        resolve({
                            json: true,
                            data: json,
                        })
                    }
                }
            } catch (err) {
                resolve({
                    data: arraybuffer,
                });
            }
        };
        reader.readAsText(blob);
    });
};

const downloadBlobFile = (blob, fileName) => {
    if (window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveBlob(blob, fileName);
    } else {
        let link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        // window.URL.revokeObjectURL(link.href);
        link.click();
    }
};

const letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
    'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
export const toRadix = index => {
    let list = [];
    const remain = index % letters.length;
    list.push(letters[remain]);
    const nextIndex = parseInt(String(index / letters.length));
    if (nextIndex > 0) {
        list = [toRadix(nextIndex - 1)].concat(list);
    }
    return list.join('');
};

export const eachTableField = fields => {
    const list = [];
    if (utils.isNotEmptyList(fields)) {
        fields.forEach(item => {
            const obj = {
                name: item.label,
                value: item.prop,
                titleBold: '1',
            };
            if (item.exportWidth) {
                obj.width = item.exportWidth;
            }
            if (item.exportMinWidth) {
                obj.minWidth = item.exportMinWidth;
            }
            if (item.exportSum) {
                obj.sum = '1';
            }
            if (item.exportDataFormat) {
                obj.dataFormat = item.exportDataFormat;
            }
            if (item.exportFormula) {
                obj.formula = '1';
            }
            if (item.exportTitleBg) {
                obj.titleBg = item.exportTitleBg;
            }
            if (item.exportAlignment) {
                obj.alignment = item.exportAlignment;
            }
            if (item.exportVertical) {
                obj.vertical = item.exportVertical;
            }
            if (item.exportTitleShrinkToFit) {
                obj.titleShrinkToFit = '1';
            } else if (item.exportTitleWrap) {
                obj.titleWrap = '1';
            }
            if (item.exportTitleBold === false) {
                delete obj.titleBold;
            }
            if (item.exportTitleSize) {
                obj.titleSize = item.exportTitleSize;
            }
            if (item.exportContentSize) {
                obj.contentSize = item.exportContentSize;
            }
            if (item.exportContentShrinkToFit) {
                obj.contentShrinkToFit = '1';
            } else if (item.exportContentWrap) {
                obj.contentWrap = '1';
            }
            if (item.exportBorderColor) {
                obj.borderColor = item.exportBorderColor;
            }
            if (item.isInteger) {
                obj.integer = '1';
            }
            if (item.isNumber) {
                obj.number = '1';
            }
            if (item.isAmount) {
                obj.amount = '1';
            }
            if (item.isDate) {
                obj.date = '1';
            }
            if (item.isDateTime) {
                obj.datetime = '1';
            }
            if (utils.isNotEmptyList(item.children)) {
                obj.children = eachTableField(item.children);
            }
            if (typeof item.export === 'undefined' || item.export) {
                list.push(obj);
            }
        });
    }
    return list;
};

export const downloadExcelFile = (arraybuffer, output_name, with_date = false) => {
    let dateName = utils.formatDate(new Date(), 'yyyy-MM-dd');
    output_name = output_name.replace(/\.xlsx/g, '');
    output_name = output_name.replace(/\.xls/g, '');
    let fileName = `${output_name}${with_date ? '_' + dateName : ''}.xlsx`;
    let blob = new Blob([arraybuffer], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
    });
    downloadBlobFile(blob, fileName);
}

export const exportExcel4MultiHead = (params = {}, titleField = [], outputName = '导出') => {
    if (params.freezeTitle === false) {
        delete params.freezeTitle;
    } else {
        params.freezeTitle = '1';
    }
    if (typeof params.dr === 'undefined') {
        params.dr = 0;
    }
    request({
        url: constants.API_ExportExcel4MultiHead,
        data: {
            ...params,
            titleField,
            outputName,
        },
        responseType: 'arraybuffer',
        timeout: 10 * 60 * 1000,
    }).then(res => {
        return procArraybuffer(res);
    }).then(res => {
        if (res.json) {
            const jsonData = res.data;
            if (jsonData.code !== 0) {
                if (utils.isNotEmpty(jsonData.message)) {
                    message.error(jsonData.message);
                }
                return;
            }
            let url = `${window.configs.requestPrefix}${constants.File_GetFile}${utils.getAccountSetSidEndWithSlash()}${jsonData.sid}`;
            download({url, name: outputName});
        } else {
            downloadExcelFile(res.data, outputName, true);
        }
    }).catch(err => {
        if (utils.isNotEmpty(err.message)) {
            message.error(err.message);
        }
    });
};
